// ==UserScript==
// @name        Steam Inventory Quick Sell Button
// @namespace   madjoki
// @include     http://steamcommunity.com/id/*/inventory/*
// @version     14
// @grant       none
// ==/UserScript==

(function (){

try
{
    // Ensure we have wallet data (user is logged in)
    if (typeof(window.g_rgWalletInfo) === "undefined")
        return;
    
    var selectedItem = null;
    var wallet = window.g_rgWalletInfo;
    
    // Ensure we have valid wallet currency. Default to US$.
    if (typeof(wallet.wallet_country) === "undefined" || typeof(wallet.wallet_currency) === "undefined" || wallet.wallet_country == '' || !wallet.wallet_currency) {
        wallet.wallet_country = 'US';
        wallet.wallet_currency = 1;
    }
    
    $J('\
    <style type="text/css">\
        #inv_settings { display: none; }\
        .item_market_orders table { margin: auto; }\
        .orders_summary { text-align: center; }\
        .orders_table { margin-bottom: 0.5em; }\
        .market_commodity_orders_table tr:nth-child(even) { background-color: #262626; }\
        .market_commodity_orders_table td, .market_commodity_orders_table th { min-width: 100px; text-align: center; }\
    </style>').appendTo("head");
    
    $J('body').append('\
    <div id="inv_settings" class="market_modal_dialog">\
        <div class="market_dialog_title">\
            <span>\
            Settings\
            <span class="market_dialog_cancel">\
                <a href="#" class="market_dialog_title_cancel">Close<span class="market_dialog_title_cancel_X">X</span></a>\
            </span>\
        </div>\
        <div class="market_dialog_contents">\
        </div>\
    </div>');
    
    function showSettings()
    {
        window.showModal('inv_settings');
    }
    
    function closeSettings()
    {
        window.hideModal('inv_settings');
    }
    
    function get_cents(text) {
        return window.SellItemDialog.GetPriceValueAsInt(text);
    }
    function currencyformat(cents) {
        return window.v_currencyformat(cents, window.GetCurrencyCode(wallet.wallet_currency));
    }
    function unique_values(array) {
        return $J.grep(array, function (el, index) {
            return index == $J.inArray(el, array);
        });
    }
    function triggerMouseEvent(node, eventType) {
        var clickEvent = document.createEvent('MouseEvents');
        clickEvent.initEvent(eventType, true, true);
        node.dispatchEvent(clickEvent);
    }
    
    function set_sell_price(text)
    {
         $J('#market_sell_buyercurrency_input').val(text);
        
        // Let Steam handle and validate changed value
         SellItemDialog.OnBuyerPriceInputKeyUp(null);
    }
    
    function quick_sell_click() {
        // Open sell window
        window.SellCurrentSelection();
       set_sell_price( $J(this).children('.item_market_action_button_contents') .text() );
        
        triggerMouseEvent($J('#market_sell_dialog_accept') [0], 'click');
        
        // Prevent default handler
        return false;
    }
    
    function get_buy_orders_by_market_url(market_url, callback) {
        if (localStorage.getItem('marketid_' + market_url) === null) {
            var oReq = new XMLHttpRequest();
            oReq.onload = function () {
                //
                var m = /Market_LoadOrderSpread\( (\d+) \)/.exec(this.responseText);
                if (m) {
                    localStorage['marketid_' + market_url] = m[1];
                    get_buy_orders_by_market_id(m[1], callback);
                }
            };
            oReq.onerror = function () {
                console.error(this.statusText);
            }
            oReq.open('get', market_url);
            oReq.send();
        } else {
            get_buy_orders_by_market_id(localStorage['marketid_' + market_url], callback);
        }
    }
    
    function get_buy_orders_by_market_id(market_id, callback) {
        var history_url = '//steamcommunity.com/market/itemordershistogram?country=' + wallet.wallet_country + '&language=' + window.g_strLanguage + '&currency=' + wallet.wallet_currency + '&item_nameid=' + market_id;
        if (history_url in cache2) {
            callback(cache2[history_url]);
        } else {
            var oReq = new XMLHttpRequest();
            oReq.onload = function () {
                var j = JSON.parse(this.responseText);
                cache2[history_url] = j;
                callback(j);
            }
            oReq.onerror = function () {
                console.error(this.statusText);
            }
            oReq.open('get', history_url);
            oReq.send();
        }
    }
    
    function addQuickSellButtons(itemid, prices)
    {
        $J.each(prices, function (index, value) {
            var btn = $J('<a href="#" class="item_market_action_button item_market_action_button_green"><span class="item_market_action_button_edge item_market_action_button_left"></span><span class="item_market_action_button_contents"></span><span class="item_market_action_button_edge item_market_action_button_right"></span><span class="item_market_action_button_preload"></span></a>');
            $J(btn) .children('.item_market_action_button_contents') .text(currencyformat(value));
            $J(btn) .click(quick_sell_click);
            $J('#iteminfo' + itemid + '_item_market_actions') .append(btn);
        });        
    }
    
    setInterval(function ()
    {
        if (selectedItem != g_ActiveInventory.selectedItem)
            updateWithSelectedItem();

    }, 200);

    function updateWithSelectedItem() {
        var itemid = window.iActiveSelectView;
        selectedItem = window.g_ActiveInventory.selectedItem;

        // Item needs to be marketable
        if (!selectedItem.marketable) {
            $J('#iteminfo' + itemid + '_market_orders').hide();
            return;
        }

        // Show buy & sell orders for commodities
        if (selectedItem.commodity)
        {
            $J('#iteminfo' + itemid + '_market_orders').show();
            $J('#iteminfo' + itemid + '_market_orders').html('Loading buy & sell orders...');

            // Get market id, so we can fetch buy & sell orders
            get_buy_orders_by_market_url($J('#iteminfo' + itemid + '_item_market_actions > div > div a:eq(0)').attr('href'), function (j)
            {
                $J('#iteminfo' + itemid + '_market_orders') .html('\
                    <div class="orders_summary" id="sell_order_summary_' + itemid + '"></div>\
                    <div class="orders_table" id="sell_order_table_' + itemid + '"></div>\
                    <div class="orders_summary" id="buy_order_summary_' + itemid + '"></div>\
                    <div class="orders_table" id="buy_order_table_' + itemid + '"></div>'
                );

                $J('#sell_order_summary_' + itemid).html(j.sell_order_summary);
                $J('#sell_order_table_' + itemid).html(j.sell_order_table);
                $J('#buy_order_summary_' + itemid).html(j.buy_order_summary);
                $J('#buy_order_table_' + itemid).html(j.buy_order_table);

                var buyOrderMax = get_cents($J('#buy_order_summary_' + itemid + ' .market_commodity_orders_header_promote:eq(1)') .text());
                var sellOrderMin = get_cents($J('#sell_order_summary_' + itemid + ' .market_commodity_orders_header_promote:eq(1)') .text());
                var common_values = [];

                if (sellOrderMin) {
                    common_values.push(sellOrderMin);
                    // 3 cents is min price
                    if (sellOrderMin > 3)
                        common_values.push(sellOrderMin - 1);
                } else {
                    sellOrderMin = 3;
                }

                if (buyOrderMax)
                    common_values.push(buyOrderMax);

                var extra_values = [];

                for (var i = sellOrderMin - 5; i <= sellOrderMin + 5; i++)
                    if (i > 2 && i >= buyOrderMax && common_values.indexOf(i) == - 1)
                        extra_values.push(i);

                addQuickSellButtons(itemid, unique_values(common_values));
                addQuickSellButtons(itemid, unique_values(extra_values));
            }); 
        }
        // Otherwise show just quick sell buttons
        else
        {
            addQuickSellButtons(itemid, [3, 4, 5, 6, 7, 8, 9, 10]);
            
            return;
        }
    }

    // Inventory page
    if (/inventory/.exec(window.location.pathname))
    {
        var cache2 = {};
        
        // Check SSA agreement.
        $J('#market_sell_dialog_accept_ssa') .attr('checked', 'checked');
        // Styles
        
        // Add div to both iteminfo sections. Steam alternates between two to provide fade animation.
        for (var i = 0; i < 2; i++) {
            $J('#iteminfo' + i + '_market_content') .append('<div id="iteminfo' + i + '_market_orders" class="item_market_actions item_market_orders"></div>');
            $J('#iteminfo' + i + '_market_orders') .hide();
        }
        
        $J('#inventories').on('click', '.itemHolder, .newitem', updateWithSelectedItem );
    } 
    // Market Page
    else if (/market/.exec(window.location.pathname))
    {
        /*$J('div.my_listing_section:eq(0) div.market_listing_my_price .market_table_value').each(function (i, el)
        {
            var price = SellItemDialog.GetPriceValueAsInt( $J(el).children('.market_listing_price').text() );
            var feeInfo = CalculateAmountToSendForDesiredReceivedAmount( price, g_rgWalletInfo['wallet_publisher_fee_percent_default'] );
            $J(el).append(" (" + v_currencyformat(price + feeInfo.fees, GetCurrencyCode(g_rgWalletInfo.wallet_currency)) + ")");
        });*/
    }
}
catch (err)
{
    window.alert(err);
}
    
})();
